package com.example.mobile2021606134chhnewdemo.ContactModule;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mobile2021606134chhnewdemo.MapModule.GaoDeMapDataManager;
import com.example.mobile2021606134chhnewdemo.NewsModule.Headline;
import com.example.mobile2021606134chhnewdemo.NewsModule.SpeedNewsDataManager;
import com.example.mobile2021606134chhnewdemo.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;



public class SpeedRobotActivity extends AppCompatActivity {
    private ListView listView;
    private ChatAdapter adpter;
    private List<ChatBean> chatBeanList;
    private EditText et_send_msg;
    private Button btn_send;
    private static final String WEB_SITE = "https://jisuiqa.market.alicloudapi.com/iqa/query";
    private static final String KEY = "https://market.aliyun.com/products/57126001/cmapi033508.html?spm=5176.2020520132.101.7.2ae272180MbpUl#sku=yuncode2750800001";    //购买地址
    private String sendMsg;
    private String welcome[];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_speed_robot);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.item_new_content_bar);
        initTitleBar();
        chatBeanList = new ArrayList<ChatBean>();
        welcome = getResources().getStringArray(R.array.welcome);
        initView();
    }

    private void initTitleBar() {
        View viewNewContentBack = findViewById(R.id.viewNewContentBack);
        View viewNewContentShare = findViewById(R.id.viewNewContentShare);
        View viewNewContentMore = findViewById(R.id.viewNewContentMore);
        viewNewContentBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewNewContentShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        viewNewContentMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.list1);
        et_send_msg = (EditText) findViewById(R.id.et_send_msg1);
        btn_send = (Button) findViewById(R.id.btn_send1);
        adpter = new ChatAdapter(chatBeanList, this);
        listView.setAdapter(adpter);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sendData();
            }
        });
        et_send_msg.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() ==
                        KeyEvent.ACTION_DOWN) {
                    sendData();
                }
                return false;
            }
        });
        int position = (int) (Math.random() * welcome.length - 1);
        showData(welcome[position]);
    }

    private void sendData() {
        sendMsg = et_send_msg.getText().toString();
        if (TextUtils.isEmpty(sendMsg)) {
            Toast.makeText(this, "还未输任何信息", Toast.LENGTH_LONG).show();
            return;
        }
        et_send_msg.setText("");
        //替换换行
        sendMsg = sendMsg.replaceAll("\n", "").trim();
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(sendMsg);
        chatBean.setState(chatBean.SEND);
        chatBeanList.add(chatBean);
        adpter.notifyDataSetChanged();
        getDataFromServer();
    }

    private void getDataFromServer() {
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("question", sendMsg)
                .build();
        Request request = new Request.Builder()
                .addHeader("Authorization", "APPCODE " + KEY)
                .url(WEB_SITE)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        SpeedRobot speedRobot = gson.fromJson(result, SpeedRobot.class);
                        String res = speedRobot.getResult().getContent();
                        if (res.equals(ChatBean.ErrorMessage)) {
                            res = "我好像没有听懂。如果有什么其他我能帮上忙的，请尽管告诉我。";
                        }
                        showData(res);
                    }
                });

            }
            @Override
            public void onFailure(Call call, IOException e) {
            }
        });
    }

    private void showData(String message) {
        ChatBean chatBean = new ChatBean();
        chatBean.setMessage(message);
        chatBean.setState(ChatBean.RECEIVE);
        chatBeanList.add(chatBean);
        adpter.notifyDataSetChanged();
    }


    protected long exitTime;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}